<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="会员名" prop="memberId">
        <el-autocomplete
          class="inline-input"
          v-model="memberName"
          :fetch-suggestions="querySearchMember"
          placeholder="请输入手机号"
          :fit-input-width="true"
          @select="handleMemberSelect"
        >
          <template #default="{ item }">
            <el-row class="suggestion_content" :gutter="20" type="flex" justify="start">
              <el-col span="12">
                <span>{{ item.mobile }}</span>
              </el-col>
              <el-col span="12">
                <span>{{ item.nickname }}</span>
              </el-col>
            </el-row>
          </template>
        </el-autocomplete>
        <!-- <el-input v-model="formData.memberId" placeholder="请输入memberID" /> -->
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeId">
        <el-autocomplete
          class="inline-input"
          v-model="storeName"
          :fetch-suggestions="querySearchStoreName"
          :fit-input-width="true"
          placeholder="请输入店铺名"
          @select="handleStoreNameSelect">
          <template #default="{ item }">
            <span>{{ item.name }}</span>
          </template>
        </el-autocomplete>
        <!-- <el-input v-model="formData.storeId" placeholder="请输入店铺编号" /> -->
      </el-form-item>
      <el-form-item label="角色ID" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="请选择角色" @change="onRoleSelect">
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
        <!-- <el-input v-model="formData.roleId" placeholder="请输入角色ID" /> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CrewRoleApi, CrewRoleVO } from '@/api/store/storecrewrole'

/** 会员和角色关联 表单 */
defineOptions({ name: 'CrewRoleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  memberId: undefined,
  storeId: undefined,
  roleId: undefined,
})
const formRules = reactive({
  memberId: [{ required: true, message: 'memberID不能为空', trigger: 'blur' }],
  storeId: [{ required: true, message: '店铺编号不能为空', trigger: 'blur' }],
  roleId: [{ required: true, message: '角色ID不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CrewRoleApi.getCrewRole(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CrewRoleVO
    if (formType.value === 'create') {
      await CrewRoleApi.createCrewRole(data)
      message.success(t('common.createSuccess'))
    } else {
      await CrewRoleApi.updateCrewRole(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    memberId: undefined,
    storeId: undefined,
    roleId: undefined,
  }
  formRef.value?.resetFields()
}

/*
会员手机搜索组件，自动填充memberId
*/
import * as memberApi from "@/api/member/user"

const memberMobile = ref("")
const memberName = ref("")
const memberList = ref<memberApi.UserVO[]>([])
const querySearchMember =async (st:string, cb:any) => {
  if(!st) return
  const data = await memberApi.getUserPage({mobile: st, pageNo: 1, pageSize: 10})
  memberList.value = data.list
  cb(data.list)
}
const handleMemberSelect = (item:memberApi.UserVO) => {
  if(item){
    formData.value.memberId = String(item.id)
    memberName.value = item.nickname
  }
}

/*
店铺名称搜索组件，自动填充storeId
*/
import * as storeApi from "@/api/mall/store"

const storeName = ref("")
const querySearchStoreName =async (st:string, cb:any) => {
  if(!st) return
  const data = await storeApi.StoreManagerApi.getStoreManagerPage({name: st, pageNo: 1, pageSize: 10})
  cb(data.list)
}
const handleStoreNameSelect = (item:storeApi.StoreManagerVO) => {
  if(item){
    formData.value.storeId = String(item.id)
    storeName.value = item.name
  }
}

/*
角色名称选择
*/
import * as RoleApi from '@/api/system/role'

const onRoleSelect = (item)=> {
  formData.value.roleId = item
}
const { roleOptions } = defineProps({
  roleOptions: {
    type: Array<RoleApi.RoleVO>,
    require: true,
    default: []
  }
})
</script>